<template>
	<view class="page-box" :style="{'background-image': 'url('+ bgUrl +')'}">
		<view style="height: 54px;"></view>
		<view class="home-container" style="display: flex;justify-content: space-between;">
			<view class="margin-t20">
				<view class="size18">您好！</view>
				<view class="size14 margin-t12">{{nowDate}}</view>
			</view>
			<view>
				<img src="@/static/images/scan.png" alt="" style="padding:10px;box-sizing: 
				;width: 32px;height: 32px;" @click="scanDevice" />
				<img src="@/static/images/add.png" alt="" style="padding:10px;box-sizing: 
				;width: 32px;height: 32px;" @click="addDevice" />
			</view>
		</view>
		<view style="margin: 50px 12px 0 12px;">
			<u-tabs :list="list" @click="onChange"></u-tabs>
		</view>
		<view class="list-content">
			<view class="list-box">
				<view v-for="(item,index) in deviceList" :key="index" class="grid-item-box" @click="toDetail(item)">
					<view style="display: flex;justify-content: space-between;">
						<img v-if="item.set_data9 == 1" :src="wenkongqiUrl" style="width:42px;height:42px;" alt="" />
						<img v-else-if="item.set_data9 == 2" :src="bigualuUrl" style="width:42px;height:42px;" alt="" />
						<img v-else :src="jikongqiUrl" style="width:42px;height:42px;" alt="" />
						<view @click.stop="deleteItem(item)">
							<uni-icons type="clear" size="28" color="#007aff"></uni-icons>
						</view>
					</view>
					<view style="display: flex;align-items: center;margin-top: 10px;">
						<view class="size14" style="color: #333333;margin-right: 10px;">
							{{item.set_data9 == 1 ? '温控器' : item.set_data9 == 2 ?  '壁挂炉':'集控器'}}
						</view>
						<img v-if="item.setStatus == 0" src="@/static/images/在线.png" style="width:12px;height:12px"
							alt="" />
						<img v-if="item.setStatus == 1" src="@/static/images/离线.png" style="width:12px;height:12px"
							alt="" />
					</view>
					<view class="size12 text-ellipsis" style="color: #666666;margin-top: 5px;">设备型号:{{item.set_data10}}
					</view>
					<view class="size12 text-ellipsis" style="color: #666666;margin-top: 5px;">设备别名:{{item.setAlias}}
					</view>
					<view class="size12 text-ellipsis" style="color: #666666;margin-top: 5px;">sn:{{item.setUuid}}
					</view>
				</view>
			</view>
		</view>
		<!-- 		<view class="add-btn" >
			<img src="@/static/images/menuadd.png" alt="" />
		</view> -->

		<uni-popup ref="popupRef" :mask-click="false" border-radius="10px 10px 0 0">
			<view style="width:300px;background-color: #ffffff;border-radius: 20px;padding: 30px 20px 10px 20px;box-sizing: border-box
		;">
				<view class="size18" style="color: #333333;font-weight: bold;">手动添加</view>
				<view class="size16" style="color: #333333;margin-top: 15px;">请输入SN号</view>
				<input class="uni-input" v-model="unit_uuid"
					style="border-bottom: 1px solid #666666;margin-top: 10px;padding: 10px 0;" maxlength="50"
					placeholder="请输入SN号" />
				<view style="display: flex;align-items: center;justify-content: flex-end;margin-top: 10px;">
					<view class="size16" @click="closePopupClick" style="padding: 10px;box-sizing: 
					;">取消</view>
					<view class="size16" @click="bindDeviceClick" style="margin-left: 15px;color: #3c9cff;padding: 10px;box-sizing: 
					;">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	// 在首页监听事件
	import { eventBus } from '@/utils/bus/index.js';
	import env from "@/config/env.js";
	import {
		devceLists,
		bindDevice,
		deleteDevice
	} from "@/api/device/index.js"
	export default {
		data() {
			return {
				bgUrl: env.baseUrl + "/file/get_file?file_name=homebg.png",
				bigualuUrl: env.baseUrl + "/file/get_file?file_name=壁挂炉.png",
				wenkongqiUrl: env.baseUrl + "/file/get_file?file_name=温控器.png",
				jikongqiUrl: env.baseUrl + "/file/get_file?file_name=集控器.png",
				scrollTop: 0,
				oldScrollTop: 0,

				isFirstLoad: true,
				nowDate: "",
				list: [{
						id: 0,
						name: "全部设备"
					},
					{
						id: 1,
						name: "客厅"
					},
					{
						id: 2,
						name: "主卧"
					},
					{
						id: 3,
						name: "次卧"
					},
				],
				deviceList: [],
				activeId: 0,
				unit_uuid: ""
			};
		},
		onLoad(options) {
			if (!options.isScanning) {
				this.getDate();
				this.getDeviceLists()
			}
			//添加监听，当设备分配之后调用该方法
			let that = this;
			eventBus.on('deviceGroupUpdated', (updatedDevice) => {
				that.getDeviceLists()
			});
		},
		onShow() {

		},
		onUnload() {
			// 页面卸载时移除监听器，防止内存泄漏
			eventBus.events['deviceGroupUpdated'] = [];
		},
		onPullDownRefresh() {
			this.getDate();
			this.getDeviceLists()
			// 模拟异步请求数据
			setTimeout(() => {
				// 这里可以进行数据更新操作，例如更新列表数据
				// 假设更新完成后，调用 uni.stopPullDownRefresh 结束下拉刷新
				uni.stopPullDownRefresh();
			}, 2000);
		},
		methods: {
			onChange(item) {
				this.activeId = item.id
				this.getDeviceLists();
			},
			async getDeviceLists() {
				let params = {
					id: uni.getStorageSync("user_info").id, //用户ID
					pactNumber: this.activeId
				}
				const res = await devceLists(params);
				if (res.status == 200) {
					this.deviceList = res.data;
				} else {
					uni.showToast({
						title: res.msg,
						icon: "none"
					});
				}
			},
			getDate() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
				const day = String(date.getDate()).padStart(2, '0'); // 补零
				this.nowDate = `今天是${year}年${month}月${day}日。`
			},
			async scanDevice() {
				const that = this;
				try {
					const scanResult = await new Promise((resolve, reject) => {
						uni.scanCode({
							url: `/pages/scan?isScanning=true`, // 传递扫码状态参数
							onlyFromCamera: true,
							success: function(res) {
								resolve(res);
							},
							fail: function(err) {
								reject(err);
							}
						});
					});
					that.unit_uuid = scanResult.result;
					if (scanResult && that.unit_uuid != "") {
						let params = {
							name: uni.getStorageSync("user_info").appName,
							phone: uni.getStorageSync("user_info").appPhone,
							password: uni.getStorageSync("user_info").appPassword,
							unit_uuid: that.unit_uuid
						};
						const bindResult = await bindDevice(params);
						if (bindResult.status === 200) {
							uni.showToast({
								title: "添加成功",
								icon: "none"
							});
							setTimeout(() => {
								that.getDeviceLists();
							}, 500)
						} else {
							uni.showToast({
								title: bindResult.msg,
								icon: "none"
							});
						}
					}
				} catch (error) {
					uni.showToast({
						title: '扫码或绑定设备出错',
						icon: "none"
					});
				}
			},
			addDevice() {
				this.unit_uuid == "";
				this.$refs.popupRef.open('center');
			},
			closePopupClick() {
				this.$refs.popupRef.close();
			},
			async bindDeviceClick() {
				if (this.unit_uuid == "") {
					uni.showToast({
						title: "请输入SN号",
						icon: "none"
					});
					return false;
				}
				let params = {
					name: uni.getStorageSync("user_info").appName,
					phone: uni.getStorageSync("user_info").appPhone,
					password: uni.getStorageSync("user_info").appPassword,
					unit_uuid: this.unit_uuid
				}
				const res = await bindDevice(params);
				if (res.status == 200) {
					this.$refs.popupRef.close();
					this.getDeviceLists();
				} else {
					uni.showToast({
						title: res.msg,
						icon: "none"
					});
				}
			},
			async deleteItem(item) {
				try {
					// 显示模态框
					const {
						confirm,
						cancel
					} = await new Promise((resolve) => {
						uni.showModal({
							title: '温馨提示',
							content: '删除当前设备？',
							success: function(res) {
								resolve(res);
							}
						});
					});

					if (confirm) {
						// 定义请求参数
						let params = {
							uuid: item.setUuid
						};

						// 调用删除设备的接口
						const deleteRes = await deleteDevice(params);

						if (deleteRes.status === 200) {
							// 删除成功提示
							uni.showToast({
								title: "删除成功",
								icon: "none"
							});
							// 重新获取设备列表
							setTimeout(() => {
								this.getDeviceLists();
							}, 800)
						} else {
							// 删除失败提示
							uni.showToast({
								title: deleteRes.msg,
								icon: "none"
							});
						}
					} else if (cancel) {
						console.log('用户点击取消');
					}
				} catch (error) {
					uni.showToast({
						title: "操作出现错误",
						icon: "none"
					});
				}
			},
			toDetail(item) {
				if (item.set_data9 == "1") {
					uni.navigateTo({
						url: "/pages/index/detail/wenkongqi?setUuid=" + item.setUuid + "&version=" + item
							.versions + "&pactNumber=" + item.pactNumber
					});
				} else if (item.set_data9 == "2") {
					uni.navigateTo({
						url: "/pages/index/detail/bigualu?setUuid=" + item.setUuid + "&version=" + item.versions +
							"&pactNumber=" + item.pactNumber
					});
				} else {
					uni.navigateTo({
						url: "/pages/index/detail/jikongqi?setUuid=" + item.setUuid + "&version=" + item.versions
					});
				}
			}
		},
	};
</script>

<style>
	.page-box {
		width: 100%;
		height: 100vh;

		background-size: contain;
		background-repeat: no-repeat;
		background-color: #F8F9F9;
	}

	.home-container {
		padding: 30px 13px 20px 23px;
		box-sizing: border-box;
	}

	.add-btn {
		position: fixed;
		left: calc(50% - 27px);
		bottom: 22px;
		z-index: 10000;
		width: 54px;
		height: 54px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.list-content {
		/* position: absolute;
		left: 10px;
		right: 10px;
		bottom: 0;
		top: 280px; */
		overflow: auto;
		margin: 10px 10px 10px 10px;
	}

	.list-box {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
	}

	.grid-item-box {
		width: calc(50% - 5px);
		/* height: 150px; */
		background-color: #FFFFFF;
		border-radius: 10px;
		padding: 11px 8px;
		box-sizing: border-box;
		/* margin-top: 10px; */
		margin-bottom: 10px;
	}
</style>